package com.freestyle.jmssample.rabbitmq.service;

import com.freestyle.jmssample.api.JMSDeclare;
import com.freestyle.jmssample.api.ManualService;
import com.freestyle.jmssample.api.SMSConstants;
import com.freestyle.jmssample.api.pojo.SMSBean;
import com.freestyle.jmssample.rabbitmq.SMSUtil;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * Created by rocklee on 2022/1/10 12:23
 */
@Service
@DependsOn("smsConfig")
@Slf4j
public class ManualServiceImp implements ManualService ,AutoCloseable, InitializingBean {
  private final static String routerKey="sms-manual-key";
  private final static String queueName="sms-manual-queue";
  @Resource
  private ConnectionFactory connectionFactory;
  @Resource
  private JMSDeclare jmsDeclare;
  private Connection recvConnection;
  private Connection sendConnection;
  private Channel recvChannel;
  private Channel sendChannel;
  @Override
  public void manualSend(SMSBean sms) throws IOException {
    sendChannel.basicPublish(SMSConstants.SMS_EXCHANGE_DIRECT,routerKey,null, SMSUtil.toByte(sms));
  }

  @Override
  public void close() throws Exception {
     recvChannel.close();
     sendChannel.close();
     recvConnection.close();
     sendConnection.close();
  }

  @Override
  public void afterPropertiesSet() throws Exception {
       if (!jmsDeclare.isQueueExists(queueName)){ //队列不存在则新建并绑定到交换机、routerkey
         jmsDeclare.initQueue(queueName);
         jmsDeclare.bindQueue(queueName,SMSConstants.SMS_EXCHANGE_DIRECT,routerKey,null);
       }
       sendConnection=connectionFactory.createConnection();
       sendChannel=sendConnection.createChannel(false);

       recvConnection=connectionFactory.createConnection();
       recvChannel=recvConnection.createChannel(false);

       //接收有两种方法，一种是直接接收
       /*GetResponse response=recvChannel.basicGet(queueName,true);
       if (response!=null){
         log.info("content:{}",SMSUtil.fromByte(response.getBody(),SMSBean.class));
       }*/
       //另一种是回调
       recvChannel.basicConsume(queueName,new DefaultConsumer(recvChannel){
         @Override
         public void handleDelivery(String consumerTag, Envelope envelope,
                                    AMQP.BasicProperties properties, byte[] body) throws IOException {
            log.info("=============consume.handleDelivery=========");
            log.info("consumerTag:{},envelope:{},properties:{}",consumerTag,envelope,properties);
            log.info("content:{}",SMSUtil.fromByte(body,SMSBean.class));
         }
       });
  }
}
